<template>
  <div class="user-custom-container">
    <el-card class="user-card">
      <div class="user-header">
        <div class="user-info">
          <h2>{{ userData.username || '未设置用户名' }}</h2>
          <p class="signature">{{ userData.signature || '这个人很懒，什么也没留下' }}</p>
        </div>
      </div>

      <div class="user-stats">
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="stat-item">
              <div class="stat-value">28</div>
              <div class="stat-label">关注</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stat-item">
              <div class="stat-value">356</div>
              <div class="stat-label">粉丝</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stat-item">
              <div class="stat-value">124</div>
              <div class="stat-label">作品</div>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <el-card class="user-details-card">
      <h3>基本信息</h3>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="手机号">
          {{ phone || '未绑定手机号' }}
        </el-descriptions-item>
        <el-descriptions-item label="性别">
          {{ userData.sex || '未设置' }}
        </el-descriptions-item>
        <el-descriptions-item label="生日">
          {{ formattedBirthday || '未设置' }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑个人资料" width="50%">
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="个性签名">
          <el-input
            v-model="editForm.signature"
            type="textarea"
            :rows="2"
            placeholder="请输入个性签名"
          ></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="editForm.sex" placeholder="请选择性别">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
            <el-option label="保密" value="保密"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="生日">
          <el-date-picker
            v-model="editForm.birthday"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditForm">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <div class="action-buttons">
      <el-button type="primary" @click="showEditDialog">编辑个人资料</el-button>
      <el-button @click="goBack">返回</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import axios from 'axios';

const router = useRouter();
const userData = ref({
  username: '',
  signature: '',
  avatar: '',
  sex: '',
  birthday: null
});

const phone = localStorage.getItem('phone');
const editDialogVisible = ref(false);
const editForm = ref({
  username: '',
  signature: '',
  sex: '',
  birthday: ''
});

// 计算格式化后的生日
const formattedBirthday = computed(() => {
  if (!userData.value.birthday) return '';

  try {
    // 尝试解析日期字符串
    const date = new Date(userData.value.birthday);

    // 检查日期是否有效
    if (isNaN(date.getTime())) {
      return userData.value.birthday; // 如果不是有效日期，直接返回原始字符串
    }

    // 格式化日期为 YYYY年MM月DD日
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');

    return `${year}年${month}月${day}日`;
  } catch (e) {
    console.error('日期格式化错误:', e);
    return userData.value.birthday; // 出错时返回原始值
  }
});

// 获取用户自定义数据
const fetchUserData = async () => {
  try {
    if (phone) {
      const response = await axios.get('http://127.0.0.1:8000/login/detail/', {
        params: { phone }
      });

      if (response.data.code === 200) {
        const detail = response.data.data.detail || {};
        userData.value = {
          username: detail.username || '',
          signature: detail.signature || '',
          avatar: detail.avatar || '',
          sex: detail.sex || '',
          birthday: detail.birthday || null
        };
      } else {
        ElMessage.error('获取用户数据失败');
      }
    }
  } catch (error) {
    console.error('获取用户自定义数据失败:', error);
    ElMessage.error('获取用户数据失败，请稍后重试');
  }
};

// 显示编辑对话框
const showEditDialog = () => {
  editForm.value = {
    username: userData.value.username || '',
    signature: userData.value.signature || '',
    sex: userData.value.sex || '',
    birthday: userData.value.birthday || ''
  };
  editDialogVisible.value = true;
};

// 提交编辑表单
const submitEditForm = async () => {
  try {
    const response = await axios.put('http://127.0.0.1:8000/login/update_detail/', {
      phone: phone,
      detail: editForm.value
    });

    if (response.data.code === 200) {
      ElMessage.success('更新成功');
      editDialogVisible.value = false;
      fetchUserData(); // 重新获取用户数据
    } else {
      ElMessage.error(response.data.message || '更新失败');
    }
  } catch (error) {
    console.error('更新用户数据失败:', error);
    ElMessage.error('更新失败，请稍后重试');
  }
};

// 导航到编辑页面
const navigateToEdit = () => {
  router.push('/usercenter/edit');
};

// 返回上一页
const goBack = () => {
  router.go(-1);
};

onMounted(() => {
  fetchUserData();
});
</script>

<style scoped>
.user-custom-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.user-card {
  margin-bottom: 20px;
}

.user-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.user-info {
  flex: 1;
}

.user-info h2 {
  margin: 0;
  font-size: 24px;
}

.signature {
  color: #666;
  margin-top: 5px;
  font-size: 14px;
}

.user-stats {
  margin: 20px 0;
}

.stat-item {
  text-align: center;
  padding: 10px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
}

.stat-label {
  color: #666;
  font-size: 14px;
}

.user-details-card {
  margin-bottom: 20px;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 20px;
}
</style>